/**
 * Created by zjm on 2017/3/6.
 */
var DBFactory = require('../db/mysql_db.js');
var async = require('async');
var VerifyCodeDao = module.exports;
var UserAppDao = require('../dao/user_app.js');
var CONFIG = require('../config.js');

// var TopClient = require('../libs/alidayu/topClient').TopClient;
// var dayuApi = new TopClient({
//     'appkey': '23708727',
//     'appsecret': '39459d33f1055cad5f83f1aa76b7994a',
//     'REST_URL': 'http://gw.api.taobao.com/router/rest'
// });
const DYSMS  = require('waliyun').DYSMS;
const smsApi = DYSMS({
    AccessKeyId:CONFIG.SMS_AccessKeyId,
    AccessKeySecret:CONFIG.SMS_AccessKeySecret
});

function catchUserfullColumn(data, toSet) {
    if (data.phone) toSet.phone = data.phone;
    if (data.code) toSet.verify_code = data.code;
    if (data.type) toSet.type = data.type;
    if (data.app_sid) toSet.app_sid = data.app_sid;
    toSet.create_num = 1;
    toSet.ip = data.ip;
}

//由于create_time是表自定义生成的，
//格式为Tue Mar 07 2017 15:11:26 GMT+0800 (中国标准时间)
//我们要改成2017-03-07 15:11:26方便计算
function formatDate(strTime) {
    var date = new Date(strTime);
    var seperator1 = "-";
    var seperator2 = ":";
    var month = date.getMonth() + 1;
    var strDate = date.getDate();
    if (month >= 1 && month <= 9) {
        month = "0" + month;
    }
    if (strDate >= 0 && strDate <= 9) {
        strDate = "0" + strDate;
    }
    var formatDate = date.getFullYear() + seperator1 + month + seperator1 + strDate
        + " " + date.getHours() + seperator2 + date.getMinutes()
        + seperator2 + date.getSeconds();
    return formatDate;
}

//type = 1：注册成功
//type = 2：输入5次都错
function deleteVerifyCode(connection, cb, data, success, type) {
    connection.query('delete from verify_codes where phone = ? and app_sid = ?',
        [data.account, data.app_sid],
        function (err, result) {
            if (err) {
                cb(err);
                return;
            } else if (result.affectedRows) {
                if (type == 1) {
                    cb(null, success);
                } else {
                    cb(success);
                }
            } else {
                cb('找不到要删除的验证码');
            }
            connection.release();
        });
}

//验证码验证成功，删除该ip
function deleteIp(connection, cb, ip) {
    connection.query('delete from ip where ip = ?', [getIp4(ip)], function (err, result) {
        if (err) {
            cb(err);
            return;
        } else {
            cb(null, '共' + result.affectedRows + '受影响！');
        }
    });
}

//判断是否是同一天
function compareTime(timeOld, timeNew) {
    //截取字符串，得到日期部分"2009-12-02",用split把字符串分隔成数组
    var begin1 = formatDate(timeOld).substr(0, 10).split("-");
    var begin2 = formatDate(timeNew).substr(0, 10).split("-");

    //将拆分的数组重新组合，并实例成化新的日期对象
    var date1 = new Date(begin1[1] + -+begin1[2] + -+begin1[0]);
    var date2 = new Date(begin2[1] + -+begin2[2] + -+begin2[0]);

    //得到两个日期之间的差值m，以分钟为单位，或用boolean
    var m = parseInt(Math.abs(date2 - date1) / 1000 / 60);
    return m;
}

VerifyCodeDao.verifyCodeNotDel = function (phone, cb) {

    phone = '%' + phone;
    DBFactory.poolQuery('select * from verify_codes where phone LIKE  ? ',
        [phone],
        function () {
            cb("no connection");
        },
        function (err, result) {
            if (err) {
                cb('未找到验证码，请先获取验证码');
                return;
            }
            cb(null, result);
        });
}

VerifyCodeDao.verifyCheck = function (req,par, cb) {
    if (!par) {
        cb(new Error(400));
        return;
    }

    var verifyCodeInfo = {};
    verifyCodeInfo.phone = par.phone;
    verifyCodeInfo.code = par.code;
    var real_ip = req.get("X-Real-IP") || req.get("X-Forwarded-For") || req.ip;
    verifyCodeInfo.ip = getIp4(real_ip);
    verifyCodeInfo.type = par.type;
    verifyCodeInfo.app_sid = par.app_sid;

    DBFactory.getConnection(function (error, connection) {//使用transaction创建新条目
        if (error) {
            cb(error);
            return;
        }
        async.waterfall([//瀑布流，后面要等前面执行完才会执行
            function (callback) {
                connection.beginTransaction(function (err) {
                    callback(err);//对应下面的参数
                });
            },
            function (callback) {
                UserAppDao.getAppItem(verifyCodeInfo.app_sid, function (error, result) {
                    if (error) {
                        callback(error);
                        return;
                    }
                    if (result) {
                        callback(null, result);
                    }
                });
            },
            //请求注册的时候，验证account是否已注册
            //修改密码时，如果手机号还没注册就提示他去注册
            function (userInfo,callback) {
                    UserAppDao.getUserApp(verifyCodeInfo.phone, function (error, result) {
                        if (error) {
                            callback(error);
                            return;
                        }
                        if(verifyCodeInfo.type == '0'){
                            if (result && result[0]) {
                                callback("该账号已注册过，请直接登陆");
                                return;
                            }
                        }else if (verifyCodeInfo.type == '1'){
                            if(result.length == 0){
                                callback("该账号还没注册过，不能修改密码");
                                return;
                            }
                        }else if (verifyCodeInfo.type == '3'){
                            if(result && result[0] && result[0].wx_unionid){
                                callback("该手机号已被绑定，请您更换账号再试");
                                return;
                            }
                        }
                        callback(null,userInfo);
                    });
            },
            function (userInfo, callback) {
                par.app_name = userInfo.name;
                //第三步：找数据库里是否有该字段phone，并进行相应处理
                VerifyCodeDao.getVerifyCode(verifyCodeInfo, function (err, verifyInfo) {
                    if (err) {
                        callback(err);
                        return;
                    }
                    callback(null, verifyInfo);
                });
            },
            function (verifyInfo, callback) {

                // var smsCode = 'SMS_127164606';  //验证身份
                // switch (par.type){
                //     case '0'://注册用户
                //         smsCode = 'SMS_127164613';
                //         break;
                //     case '1'://重置密码
                //         smsCode = 'SMS_127159561';
                //         break;
                //     case '2'://修改用户个人资料
                //         smsCode = 'SMS_127159559';
                //         break;
                //     case '3'://用户身份绑定
                //         smsCode = 'SMS_127154609';
                //         break;
                //     case '4'://短信登录
                //         smsCode = 'SMS_127159568';
                //         break;
                //     case '5'://操作密码锁
                //         smsCode = 'SMS_127164607';
                //         break;
                // }

                var smsCode = 'SMS_135031349';  //验证身份
                switch (par.type){
                    case '0'://注册用户
                        smsCode = 'SMS_135036302';
                        break;
                    case '1'://重置密码
                        smsCode = 'SMS_135026513';
                        break;
                    case '2'://修改用户个人资料
                        smsCode = 'SMS_135041374';
                        break;
                    case '3'://用户身份绑定
                        smsCode = 'SMS_135026518';
                        break;
                    case '4'://短信登录
                        smsCode = 'SMS_135031346';
                        break;
                    case '5'://操作密码锁
                        smsCode = 'SMS_135031348';
                        break;
                    case '6'://物流单号推送
                        // smsCode = 'SMS_135044059';
                        smsCode = 'SMS_151178951';
                        break;
                }
                var signName = '乐隆昌';
                if(par.app_sid == 'usuz'){
                    signName = '微淘客';
                }else if(par.app_sid == 'duoke'){
                    signName = '多客精选';
                }
                if(par.plat == 'jntb'){
                    signName = '金牛';
                }
                var templateParam = {number:par.code};
                if (par.o_id) templateParam = {o_id: par.o_id};
                smsApi.sendSms({
                    TemplateParam: JSON.stringify(templateParam),
                    PhoneNumbers: par.phone,
                    SignName: signName,
                    TemplateCode: smsCode
                }).then(function (data) {
                    if(data.Code != 'OK'){
                        VerifyCodeDao.getError(verifyCodeInfo, function (e, d) {
                            console.log(e);
                            if(e){
                                callback(e);
                                return;
                            }
                            callback(data.Message);
                        });
                    }else {
                        if (data.length == 0){
                            callback('速度太快了');
                        }else {
                            callback(null, true, data);
                        }
                    }
                });
                
                // var smsName = '乐隆昌';
                // var smsCode = null;
                // if (par.type == 0) {
                //     // smsName = '注册验证';
                //     smsCode = 'SMS_64805022';
                // } else {
                //     // smsName = '身份验证';
                //     smsCode = 'SMS_64880026';
                // }
                //
                // //获取验证码
                // dayuApi.execute('alibaba.aliqin.fc.sms.num.send', {
                //     'extend': '123456',
                //     'sms_type': 'normal',
                //     'sms_free_sign_name': smsName,
                //     'sms_param': '{\"code\":\"' + par.code + '\",\"product\":\"' + par.app_name + '\"}',
                //     'rec_num': par.phone,
                //     'sms_template_code': smsCode
                // }, function (error, response) {
                //     if (error) {
                //         VerifyCodeDao.getError(verifyCodeInfo, function (e, d) {
                //             console.log(e);
                //             callback("服务器获取验证码失败");
                //         });
                //     }
                //     else {
                //         callback(null, true,response);
                //     }
                // })
            },
        ], function (DbErr, isSuccess, result) {
            if (DbErr) {
                connection.rollback(function () {
                    connection.release();
                    cb(DbErr);
                });
            } else if (!isSuccess) {
                connection.rollback(function () {
                    connection.release();
                    cb(result);
                });
            } else {
                connection.commit(function (e) {
                    if (e) {
                        connection.rollback(function () {
                            connection.release();
                            cb(e);
                        });
                    } else {
                        connection.release();
                        cb(null, result);
                    }
                });
            }
        });
    });
}

//判断验证码
VerifyCodeDao.verifyCode = function (data, cb) {
    if (!data) {
        cb(new Error(400));
        return;
    }
    DBFactory.getConnection(function (error, connection) {
        if (error) {
            cb(error);
            return;
        }
        connection.query('select * from verify_codes where phone = ? and type = ? and app_sid = ?',
            [data.account, data.type, data.app_sid],
            function (err, result) {
                if (err) {
                    cb(err);
                    return;
                }
                if (result.length > 0) {
                    var timeInterval = (data.time - result[0].create_time) / 1000;

                    if (timeInterval > 1800) {
                        cb('过期的验证码，请重新获取');
                        connection.release();
                        return;
                    }
                    console.log(data.ip);
                    var err_num = result[0].err_num;
                    if (data.verifycode == result[0].verify_code) {
                        deleteIp(connection, function () {
                            deleteVerifyCode(connection, cb, data, result, 1);
                        }, data.ip);
                        return;
                    }
                    if (err_num == 5) {
                        deleteVerifyCode(connection, cb, data, '验证码输入次数超过5次，请重新获取', 2);
                        return;
                    }
                    connection.query('update verify_codes set err_num = ? where phone = ? and type =? and app_sid = ?',
                        [err_num + 1, data.account, data.type, data.app_sid],
                        function (err, result) {
                            if (err) {
                                cb(err);
                                return;
                            }
                            else if (result.affectedRows) {
                                cb('验证码输入错误' + (err_num + 1) + '次');
                            } else {
                                cb('更新错误次数失败');
                            }
                            connection.release();
                        });
                    return;

                } else if (result.length <= 0) {
                    cb('未找到验证码，请先获取验证码');
                    connection.release();
                }
            });
    })
}

//判断ip是否受限
function isVailidIp(ip, cb) {
    if (!ip) {
        cb('获取验证码时发生错误！');
    } else {
        DBFactory.poolQuery('select create_num as count , create_time from ip where ip = ?', [ip],
            function () {
                cb("no connection");
            },
            function (err, result, connection) {
                if (err) {
                    console.log(err);
                    cb(err);
                    return;
                } else {
                    var day = new Date();
                    day = day.getDate();
                    if (result[0] !== undefined) {
                        var old_day = result[0].create_time + '';
                        old_day = parseInt(old_day.substring(8, 10));
                    } else {
                        old_day = null;
                    }
                    var sameDay = (day === old_day) ? true : false;
                    if (result[0] == undefined || !sameDay) {
                        connection.query('replace into ip set ?', {
                            ip: ip,
                            create_num: 1
                        }, function (e, r) {
                            if (e) {
                                console.log(r);
                                cb(e);
                            } else {
                                cb(null, true);
                            }
                            connection.release();
                        });
                        return true;
                    } else if (result[0].count <= 200) {
                        connection.query('update ip set create_num = create_num + 1 , create_time = CURRENT_TIMESTAMP where' +
                            ' ip = ? ', [ip], function (e) {
                            if (e) {
                                console.log(e);
                                cb(e);
                            } else {
                                cb(null, true);
                            }
                            connection.release();
                        });
                        return true;
                    } else {
                        cb(null, false);
                    }
                    return false;
                }
            });
    }
}

//获取验证码接口
VerifyCodeDao.getVerifyCode = function (data, cb) {
    if (!data) {
        cb(new Error(400));
        return;
    }

    isVailidIp(data.ip, function (e, r) {
        if (e) {
            console.log(e);
            cb('获取验证码失败,请重新获取!');
            return;
        }
        if (r) {
            DBFactory.getConnection(function (error, connection) {//使用transaction创建新条目
                if (error) {
                    cb(error);
                    return;
                }
                async.waterfall([//瀑布流，后面要等前面执行完才会执行
                    // 开始Transaction
                    function (callback) {
                        connection.beginTransaction(function (err) {
                            callback(err);//对应下面的参数
                        });
                    },

                    //验证account
                    function (callback) {
                        connection.query("select * from verify_codes where phone = ? and type = ? and app_sid = ? limit 1", [data.phone, data.type, data.app_sid], function (err, result) {
                            var verifyInfoOld = (result && result.length > 0) ? result[0] : undefined;
                            callback(err, verifyInfoOld);
                        });
                    },

                    function (verifyInfoOld, callback) {
                        var toSet = {};
                        catchUserfullColumn(data, toSet);
                        if (verifyInfoOld) {//手机验证码已有录入
                            var num = verifyInfoOld.create_num;
                            var timeOld = verifyInfoOld.create_time;
                            var timeNew = new Date();
                            //判断当天限制次数是否要重新开始m为0是同一天
                            var m = compareTime(timeOld, timeNew);
                            //服务端可以不计算时间戳的，给客户端去计算，减少服务端的工作量，这里有写
                            var timeInterval = (timeNew - timeOld) / 1000;
                            if (num == 5) {//当天只能发送5次
                                if (m == 0) {//当天
                                    callback(null, false, '该用户当天访问验证码次数已达上限！');
                                } else {
                                    num = 0;
                                    connection.query('update verify_codes set create_num = ?,verify_code = ?,create_time = ? where phone = ? and type = ? and app_sid = ?',
                                        [num + 1, data.code, timeNew, data.phone, data.type, data.app_sid], function (e, result) {
                                            if (e) {
                                                callback(null, false, '更新手机验证码数据失败');
                                            }
                                            else if (result) {
                                                callback(e, true, result);
                                            }
                                        });
                                }
                            } else if (timeInterval < 60) {
                                callback(null, false, '请60秒后再发送');
                            } else {
                                if (m == 0) {
                                    num++;
                                } else {
                                    num = 1;
                                }
                                // connection.query('update verify_codes set create_num = ?,verify_code = ?,create_time = CURRENT_TIMESTAMP where phone = ? and type =?',
                                connection.query('update verify_codes set create_num = ?,verify_code = ?,create_time = ? where phone = ? and type =? and app_sid = ?',
                                    [num, data.code, timeNew, data.phone, data.type, data.app_sid], function (err, result) {
                                        if (err) {
                                            callback(null, false, '更新失败');
                                        }
                                        else if (result) {
                                            callback(err, true, result);
                                        }
                                    });
                            }
                        }
                        else {//新的手机号
                            connection.query("insert into verify_codes set ?",
                                toSet,
                                function (err, result) {
                                    callback(err, true, result);
                                });
                        }
                    },

                ], function (DbErr, isSuccess, result) {
                    if (DbErr) {
                        connection.rollback(function () {
                            connection.release();
                            cb(DbErr);
                        });
                    } else if (!isSuccess) {
                        connection.rollback(function () {
                            connection.release();
                            cb(result);
                        });
                    } else {
                        connection.commit(function (e) {
                            if (e) {
                                connection.rollback(function () {
                                    connection.release();
                                    cb(e);
                                });
                            } else {
                                connection.release();
                                cb(null, result);
                            }
                        });
                    }
                });
            });
        } else {
            cb('该ip受限，无法获取到验证码!');
        }
    });
}

//验证码  获取失败时删除已生成的数据

VerifyCodeDao.getError = function (data, cb) {
    if (!data) {
        cb(new Error(400));
        return;
    } else {
        DBFactory.poolQuery('select * from verify_codes  where phone = ? and type = ? and app_sid = ?',
            [data.phone, data.type, data.app_sid],
            function () {
                cb("no connection");

            },
            function (err, result, connection) {
                if (err) {
                    cb(err);
                    return false;
                } else {
                    // console.log("result:"+result.toString());
                    if (result[0].create_num == 1) {
                        connection.query('delete from verify_codes where phone = ? and type = ? and app_sid = ?', [data.phone, data.type, data.app_sid],
                            function (e) {
                                if (e) {
                                    cb(e);
                                    return false;
                                }
                                cb(null, true);
                                connection.release();
                            });
                        return true;
                    } else {
                        connection.query('update verify_codes set create_num = create_num - 1 where phone = ? and type = ? and app_sid = ?', [data.phone, data.type, data.app_sid],
                            function (e) {
                                if (e) {
                                    cb(e);
                                    return false;
                                }
                                cb(null, true);
                                connection.release();
                            });
                        return true;
                    }
                    connection.query('update ip set create_num = create_num -1 where ip = ?', [data.ip],
                        function (e) {
                            if (e) {
                                cb(e);
                                return false;
                            }
                            cb(null, true);
                            connection.release();
                        });
                    return true;
                }
            });
    }
}

//列出所有验证码
VerifyCodeDao.showVcodelist = function (data, cb) {
    if (!data) {
        cb(new Error(400));
        return;
    }
    var sql;
    var sqlValue = [];
    if (data.role.indexOf('adm_' + data.app_sid) >= 0) {
        sql = 'select a.phone,a.ip,a.verify_code,a.create_time,a.type,a.ip,a.app_sid,b.name from verify_codes a LEFT JOIN apps b on a.app_sid = b.sid where app_sid = ?';
        sqlValue.push(data.app_sid);
        if (data.phone) {
            sql += " and RIGHT(phone,4) like ?";
            sqlValue.push('%' + data.phone + '%');
        }
    }
    if (data.role.indexOf("admin") >= 0) {
        sql = 'select a.phone,a.ip,a.verify_code,a.create_time,a.type,a.ip,a.app_sid,b.name from verify_codes a LEFT JOIN apps b on a.app_sid = b.sid';
        if (data.phone) {
            sql += " where RIGHT(phone,4) like ?";
            sqlValue.push('%' + data.phone + '%');
        }
        if (data.app_sid) {
            if (data.phone) {
                sql += " and app_sid = ?";
                sqlValue.push(data.app_sid);
            } else {
                sql += " where app_sid = ?";
                sqlValue.push(data.app_sid);
            }
        }
    }
    DBFactory.poolQuery(sql,
        sqlValue,
        function () {
            cb("no connection");
        },
        function (err, result) {
            if (err) {
                cb('未找到验证码，请先获取验证码');
                return;
            }
            cb(null, result);
        });

}

//删除指定的验证码
VerifyCodeDao.delVcode = function (data, cb) {
    if (!data) {
        cb(new Error(400));
        return;
    }
    var sql;
    var sqlValue = [];
    if (data.role.indexOf("admin") >= 0 || data.role.indexOf('adm_' + data.app_sid) >= 0) {
        sql = 'delete from verify_codes where app_sid = ? and phone = ? and verify_code = ?';
        sqlValue.push(data.app_sid, data.phone, data.vcode);
        DBFactory.poolQuery(sql,
            sqlValue,
            function () {
                cb("no connection");

            }, function (err, result) {
                if (err) {
                    cb(err);
                    return;
                }
                if (result.affectedRows > 0) {
                    cb(null, '操作成功');
                } else {
                    cb('操作失败');
                }
            });
    }
}


//列出所有ip
VerifyCodeDao.showIp = function (data, cb) {
    var sql = 'select * from ip';
    var sqlValue = [];
    if (data.ip) {
        sql += ' where ip like ?';
        sqlValue.push('%' + data.ip + '%');
    }
    DBFactory.poolQuery(sql,
        sqlValue,
        function () {
            cb("no connection");
        },
        function (err, result) {
            if (err) {
                cb(err);
                return;
            }
            cb(null, result);
        });
}

//设置ip
VerifyCodeDao.setIp = function (data, cb) {
    var sql = 'update ip set create_num = 0 where ip like ?';
    DBFactory.poolQuery(sql,
        ['%' + data.ip + '%'],
        function () {
            cb("no connection");
        },
        function (err, result) {
            if (err) {
                cb(err);
                return;
            }
            cb(null, result);
        });
}

//删除所有ip项
VerifyCodeDao.deleteIp = function (data, cb) {

    DBFactory.poolQuery('delete from ip where datediff(?, create_time)>=1', [new Date()],
        function () {
            cb("no connection");
        },
        function (err, result) {
            if (err) {
                cb(err);
                return;
            }
            if (result) {
                cb(null, result);
            } else {
                cb("修改失败");
            }
        });
}

